﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Kokomo.Xml
{
	public class TypeSchema
	{
		public TypeSchema(Type type, string elementName)
		{
			ArgumentValidation.CheckNullArgument("type", type);

			this.Type = type;
			this.ElementName = elementName;

			this.Properties = new PropertySchemaCollection();
			this.PopulateSchema(Properties);
		}

		protected virtual void PopulateSchema(PropertySchemaCollection properties)
		{
			{
				FieldInfo[] fields = this.Type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
				foreach (var field in fields)
				{
					XmlPropertyAttribute attribute = field.GetCustomAttribute<XmlPropertyAttribute>();
					if (attribute != null)
					{
						string nodeName = attribute.NodeName ?? field.Name;
						RuntimeFieldSchema schema = new RuntimeFieldSchema(field, attribute.NodeType, nodeName, 0);
						properties.Add(schema);
					}
				}
			}
			{
				PropertyInfo[] properties2 = this.Type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
				foreach (var property in properties2)
				{
					XmlPropertyAttribute attribute = property.GetCustomAttribute<XmlPropertyAttribute>();
					if (attribute != null)
					{
						string nodeName = attribute.NodeName ?? property.Name;
						RuntimePropertySchema schema = new RuntimePropertySchema(property, attribute.NodeType, nodeName, 0);
						properties.Add(schema);
					}
				}
			}
		}

		public Type Type { get; private set; }
		public PropertySchemaCollection Properties { get; private set; }
		public string ElementName { get; private set; }

	}
}
